package com.hele.sts.action;

import com.opensymphony.xwork2.Action;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

/**
 * @ClassName DemoAction
 * @Description TODO
 * @Author xuning
 * @Date 2019-05-29 14:29
 **/
public class DemoAction implements Action {

    static Logger logger = LoggerFactory.getLogger(DemoAction.class);
    private String tipInfo;

    public String getTipInfo() {
        return tipInfo;
    }

    public void setTipInfo(String tipInfo) {
        this.tipInfo = tipInfo;
    }

    private String action;

    public String getAction() {
        return action;
    }

    public void setAction(String action) {
        this.action = action;
    }

    @Override
    public String execute() throws UnsupportedEncodingException {
        if("test1".equals(action)){
            tipInfo = "test1 success";
        }else if("entList".equals(action)){
            CloseableHttpClient httpclient = HttpClients.createDefault();
            HttpPost httpPost = new HttpPost("http://10.68.140.174/GsService/Service/fuzzyHzEntInfo");

            List<NameValuePair> nvps = new ArrayList<NameValuePair>();
            nvps.add(new BasicNameValuePair("entname", URLEncoder.encode("雅戈尔","UTF-8")));
            nvps.add(new BasicNameValuePair("pagenum", "1"));
            nvps.add(new BasicNameValuePair("pagesize", "10"));
            nvps.add(new BasicNameValuePair("orderby", "HZRQ"));
            long starttime = System.currentTimeMillis();
            CloseableHttpResponse response = null;
            httpPost.setEntity(new UrlEncodedFormEntity(nvps));
            try {
                response = httpclient.execute(httpPost);
                String result= EntityUtils.toString(response.getEntity());
                System.out.println(result);
                logger.info(result);
                tipInfo = result;
            }catch (ClientProtocolException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
                logger.error("error",e);
            }

            long endtime = System.currentTimeMillis();
            String executionTime = Math.round(endtime-starttime)/1000.0+"";
            System.out.println("消耗时间"+executionTime+"秒");
            logger.info("消耗时间"+executionTime+"秒");
        }

        return "success";
    }
}
